#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/config/functions"
source "$PLUGIN_AVAILABLE_PATH/ps/functions"
source "$PLUGIN_AVAILABLE_PATH/ps/internal-functions"

cmd-ps-restore() {
  declare desc="starts all apps with DOKKU_APP_RESTORE not set to 0 via command line"
  declare cmd="ps:restore"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1"
  local DOKKU_SCHEDULER

  DOKKU_SCHEDULER=$(get_app_scheduler "$APP")
  plugn trigger pre-restore "$DOKKU_SCHEDULER" "$APP"

  if [[ -n "$APP" ]]; then
    if ! (is_deployed "$APP"); then
      dokku_log_warn "App $APP has not been deployed"
      return
    fi

    DOKKU_APP_RESTORE="$(config_get "$APP" DOKKU_APP_RESTORE || true)"
    if [[ $DOKKU_APP_RESTORE != 0 ]]; then
      ps_restore "$APP" || dokku_log_warn "dokku ps:restore ${APP} failed"
    fi
  else
    fn-ps-parallel-cmd "restore"
  fi
}

cmd-ps-restore "$@"
